<template>
  <Layout>
    <CommonHeader
      slot="header"
      :user-name="userName"
    />

    <CommonMenu
      slot="sider"
      :data="menuData"
      :active="menuActive"
      :collapsed="menuCollapsed"
    />

    <Breadcrumb
      slot="breadcrumb"
      :data="breadcrumb"
    />

    <template slot="main">
      <!-- 筛选项 -->
      <el-row
        type="flex"
        justify="space-between"
      >
        <el-col>
          <!--日期-->
          <el-date-picker
            v-model="daterangeSelect"
            type="daterange"
            align="left"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            :picker-options="daterangeOptions"
            class="u-mr10 u-mb20"
          >
          </el-date-picker>
          <!-- 公司 -->
          <el-select
            v-model="searchRequestParam.channelCode"
            filterable
            clearable
            class="u-mr10 u-mb20"
            placeholder="请选择公司"
          >
            <el-option
              v-for="item in companyList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >{{ item.label }}
            </el-option>
          </el-select>
          <!-- 产品 -->
          <el-select
            v-model="searchRequestParam.productCode"
            filterable
            clearable
            class="u-mr10 u-mb20"
            placeholder="请选择产品"
          >
            <el-option
              v-for="item in productList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >{{ item.label }}
            </el-option>
          </el-select>
          <!-- 导出数据 -->
          <el-button
            @click="importTable"
            type="primary"
            class="u-mb20"
          >导出数据</el-button>
        </el-col>
        <el-dropdown class="u-mb20">
          <el-button icon="el-icon-setting" />
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item
              v-for="(item, index) of filterPermissionTableColumn"
              :key="index"
            >
              <el-checkbox
                @click.native.stop
                v-model="item.visible"
                @change="tableFilter({index, visible: item.visible})"
              >{{item.label}}</el-checkbox>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-row>

      <!-- 表格 -->
      <el-table
        :data="tableList"
        border
        stripe
      >
        <el-table-column
          v-for="(col, index) in filterTableColumn"
          :key="index"
          :fixed="col.fixed"
          :sortable="col.sortable"
          :prop="col.prop"
          :label="col.label"
          :formatter="col.format"
          min-width="100"
        >
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-show="page.count > 0"
        :current-page.sync="page.currentPage"
        :page-sizes="page.sizes"
        :page-size="page.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.count"
        @size-change="pageSizeChange"
        @current-change="pageChange"
        class="u-mt20 u-mb20 u-tc"
      />
    </template>
  </Layout>
</template>

<script>
import CommonHeader from "@/components/header";
import Layout from "@/components/layout";
import Breadcrumb from "@/components/breadcrumb";
import CommonMenu from "@/components/menu";

import {
  daterangeOptions,
  formatSelectOption,
  export2Excel,
  sessionStorage
} from "@/util";
import { fetchRealCompany, fetchRealProduct, fetchRealSearch } from "@/api";

export default {
  name: "RealTime",
  data() {
    return {
      // 账号
      account: sessionStorage.get("Login").nick,

      // 暂时用公司名当用户名
      userName: "",

      // 左侧导航
      menuActive: "0-0",
      menuCollapsed: false,
      menuData: [
        {
          title: "CPA数据管理",
          leftIcon: "icon-2",
          rightIcon: "icon-1",
          children: [
            {
              title: "实时数据"
            }
          ]
        }
      ],

      // 面包屑
      breadcrumb: [{ label: "CPA数据管理" }, { label: "实时数据" }],

      // 日期
      daterangeSelect: null,
      daterangeOptions,

      // 公司
      companyList: [],

      // 产品
      productList: [],

      // 查询数据
      searchRequestParam: {
        // 以前就有，不知道干啥的
        type: 6,

        // 公司
        channelCode: "",

        // 产品
        productCode: ""
      },

      // 表单/表头
      tableColumn: [
        {
          prop: "dataTime",
          label: "日期",
          visible: true
        },
        {
          prop: "productName",
          label: "产品名称",
          visible: true
        },
        {
          prop: "productPackageName",
          label: "包名",
          visible: true,
          permission: ["kydspK009"]
        },
        {
          prop: "productChannelCode",
          label: "渠道号",
          visible: true
        },
        {
          prop: "channelName",
          label: "渠道名称",
          visible: true
        },
        {
          prop: "expectedAct",
          label: "预估激活",
          visible: true
        },
        {
          prop: "adjustmentAct",
          label: "结算激活",
          visible: true
        },
        {
          prop: "retention",
          label: "留存率",
          visible: true,
          format: row => {
            if (row.dataTime !== "总计") {
              return row.retention + "%";
            } else {
              return "";
            }
          }
        }
      ],

      // 表单/数据
      tableList: [],

      // 分页
      page: {
        sizes: [20, 50, 100, 200, 500],
        offset: 1,
        limit: 20,
        count: 0,
        currentPage: 1
      }
    };
  },
  computed: {
    filterPermissionTableColumn() {
      return this.tableColumn.filter(item => {
        if (item.permission) {
          return item.permission.indexOf(this.account) !== -1;
        }
        return true;
      });
    },
    filterTableColumn() {
      return this.filterPermissionTableColumn.filter(item => item.visible);
    }
  },
  watch: {
    // 公司改变时请求产品筛选数据
    "searchRequestParam.channelCode": async function(data) {
      // 清空现有的产品数据
      this.productList = [];
      this.searchRequestParam.productCode = "";
      // 请求数据
      await this.getRealProduct(data);
      await this.getRealTimeList();
    },
    // 产品
    "searchRequestParam.productCode"() {
      this.getRealTimeList();
    },
    // 日期筛选有数据变化就重新请求
    daterangeSelect() {
      this.getRealTimeList();
    }
  },
  methods: {
    // 公司下拉选项
    getRealCompany() {
      fetchRealCompany()
        .then(res => {
          this.companyList = formatSelectOption(res.channels);
          this.userName = this.companyList[0].label;
        })
        .catch(() => {});
    },

    // 产品下拉选项
    getRealProduct(channelCode) {
      fetchRealProduct({
        param: {
          channelCode
        }
      })
        .then(res => {
          this.productList = formatSelectOption(
            res.items,
            "productName",
            "productCode"
          );
        })
        .catch(() => {});
    },

    // 查询，[日期、公司、产品]有一个条件就能查到数据
    getRealTimeList() {
      // 暂时修改为日期和公司选了就能出数据，之后会让后台限制账户权限
      if (!this.daterangeSelect || this.searchRequestParam.channelCode === "") {
        this.page.count = 0;
        this.page.offset = 1;
        this.page.currentPage = 1;
        this.tableList = [];
        return;
      }
      let instance = this.$loading({
        fullscreen: true,
        text: "加载中...",
        background: "rgba(0, 0, 0, 0.7)"
      });
      fetchRealSearch({
        param: Object.assign({}, this.searchRequestParam, {
          // 日期段
          sDataTime: this.daterangeSelect[0],
          eDataTime: this.daterangeSelect[1],
          // 分页
          curPage: this.page.offset,
          limit: this.page.limit
        })
      })
        .then(res => {
          instance.close();
          let data = res.list;
          if (data.length) {
            // 第一行要添加留存率总计
            data.unshift({
              dataTime: "总计",
              adjustmentAct: res.settlementActTotal
            });
          }
          this.page.count = res.totalNums;
          this.tableList = data;
        })
        .catch(() => {});
    },

    // 每页条数改变
    pageSizeChange(size) {
      this.page.limit = size;
      this.page.offset = 1;
      this.getRealTimeList();
    },

    // 页码改变
    pageChange(offset) {
      this.page.offset = offset;
      this.getRealTimeList();
    },

    // 表格筛选
    tableFilter({ index, visible }) {
      let ret = this.filterPermissionTableColumn.filter(item => {
        return item.visible === true;
      });
      this.filterPermissionTableColumn[index].visible =
        ret.length > 0 ? visible : true;
    },

    // 获取visible的表头
    getTableColumn(key) {
      let ret = [];
      this.filterPermissionTableColumn.forEach(item => {
        if (item.visible) {
          ret.push(item[key]);
        }
      });
      return ret;
    },

    // 导出数据
    importTable() {
      if (!this.tableList.length) {
        return this.$message.error("没有可导出的数据！");
      }
      let tHeader = this.getTableColumn("label"),
        filterVal = this.getTableColumn("prop"),
        fileName = [
          this.daterangeSelect[0],
          this.daterangeSelect[1],
          this.searchRequestParam.channelCode,
          this.searchRequestParam.productCode,
          "实时数据"
        ].join("_");

      export2Excel(tHeader, filterVal, this.tableList, fileName);
    }
  },
  created() {
    this.getRealCompany();
  },
  components: {
    CommonHeader,
    Layout,
    Breadcrumb,
    CommonMenu
  }
};
</script>
